#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_FormMisc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update, COOPGIS_FormStaker
import COOPGIS_FormGeography, COOPGIS_DynamicTemplate
from djangoproject.models import *
import os, csv, shutil, datetime, time, reportlab, djangoproject.settings, random
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.http import HttpResponse
from django.contrib import admin
from django.template import Context, loader
import djangoproject.settings
import _mysql as mysql
from models import *
from django import forms



from django.db import transaction



@transaction.commit_on_success
def MainMenu(request):
    """MainMenu is the main selection and edit screen for a Staker Work Order (heading fields), links into WorkOrderDetails)."""
    ApplicationName=djangoproject.settings.COOPGISStakerApplicationName
    UserNameOrIPAddress, DefaultMap=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=True, ApplicationName=ApplicationName)
    LoginStatus, applicationPermission=COOPGIS_Misc.CheckLoginPermissions(request, ApplicationName)
    form=COOPGIS_FormMisc.BuildForm(request, ApplicationName, DefaultMap)
    if(not applicationPermission):
        t = loader.get_template('/opt/coopgis/djangoproject/templates/stakermainmenu.html')
        c = Context({'form': form, 'LoginStatus':LoginStatus})
        return HttpResponse(t.render(c))
    SpecialBuildFormInfo={}
    SpecialBuildFormInfo['QueryUserName']=COOPGIS_FormMisc.FormGetString(form, 'QueryUserName', Default='All')
    SpecialBuildFormInfo['ShowStakerIndicator']=COOPGIS_FormMisc.FormGetBoolean(form, 'ShowStakerIndicator')
    SpecialBuildFormInfo['ShowOutToConstructionIndicator']=COOPGIS_FormMisc.FormGetBoolean(form, 'ShowOutToConstructionIndicator')
    SpecialBuildFormInfo['ShowVerificationIndicator']=COOPGIS_FormMisc.FormGetBoolean(form, 'ShowVerificationIndicator')
    SpecialBuildFormInfo['ShowArchivedIndicator']=COOPGIS_FormMisc.FormGetBoolean(form, 'ShowArchivedIndicator')
    SpecialBuildFormInfo['ShowDeletedIndicator']=COOPGIS_FormMisc.FormGetBoolean(form, 'ShowDeletedIndicator')

    form=COOPGIS_FormMisc.BuildForm(request, ApplicationName, DefaultMap, SpecialBuildFormInfo=SpecialBuildFormInfo)
    form=COOPGIS_FormStaker.ProcessStakerFormSelectWorkOrder(form, UserNameOrIPAddress)
    stakerWorkOrder, SelectedWorkOrderid, ArchiveStatusMessage, StakerWorkOrderNumberMessage = COOPGIS_FormStaker.ProcessStakerForm(form, UserNameOrIPAddress, request)
    SelectedWorkOrderid = COOPGIS_FormStaker.PopulateStakerForm(form, stakerWorkOrder, SelectedWorkOrderid, UserNameOrIPAddress)
    try:
        ViewScannedIndicator=bool(stakerWorkOrder.ArchivedScannedWorkOrderFileName)
    except:
        ViewScannedIndicator=False
    try:
        ViewInspectedIndicator=bool(stakerWorkOrder.ArchivedInspectedWorkOrderFileName)
    except:
        ViewInspectedIndicator=False
    try:
        ArchivedIndicator=bool(stakerWorkOrder.ArchivedIndicator)
    except:
        ArchivedIndicator=False
    t = loader.get_template('/opt/coopgis/djangoproject/templates/stakermainmenu.html')
    c = Context({'form': form, 'LoginStatus': LoginStatus, 'ViewScannedIndicator': ViewScannedIndicator,
                 'SelectedWorkOrderid': SelectedWorkOrderid, 'ArchiveStatusMessage': ArchiveStatusMessage,
                 'ArchivedIndicator': ArchivedIndicator, 'StakerWorkOrderNumberMessage': StakerWorkOrderNumberMessage,
                 'ViewInspectedIndicator': ViewInspectedIndicator})
    return HttpResponse(t.render(c))

@transaction.commit_on_success
def GenerateReport(request, StakerWorkOrderid):
    ApplicationName=djangoproject.settings.COOPGISStakerApplicationName
    UserNameOrIPAddress=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=False, ApplicationName=ApplicationName)
    LoginStatus, applicationPermission=COOPGIS_Misc.CheckLoginPermissions(request, ApplicationName)
    if(not applicationPermission):
        t = loader.get_template('/opt/coopgis/djangoproject/templates/stakergeneratereport.html')
        c = Context({'LoginStatus' : LoginStatus})
        return HttpResponse(t.render(c))
    GenerateReportStatus, ReportLocation=COOPGIS_FormStaker.GenerateReportDetails(StakerWorkOrderid, UserNameOrIPAddress)
    t = loader.get_template('/opt/coopgis/djangoproject/templates/stakergeneratereport.html')
    c = Context({'LoginStatus' : LoginStatus, 'GenerateReportStatus': GenerateReportStatus, 'ReportLocation': ReportLocation})
    return HttpResponse(t.render(c))

@transaction.commit_on_success
def ViewScanned(request, StakerWorkOrderid):
    ApplicationName=djangoproject.settings.COOPGISStakerApplicationName
    UserNameOrIPAddress=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=False, ApplicationName=ApplicationName)
    LoginStatus, applicationPermission=COOPGIS_Misc.CheckLoginPermissions(request, ApplicationName)
    if(not applicationPermission):
        t = loader.get_template('/opt/coopgis/djangoproject/templates/stakergeneratereport.html')
        c = Context({'LoginStatus' : LoginStatus})
        return HttpResponse(t.render(c))
    GenerateReportStatus, ReportLocation=COOPGIS_FormStaker.GenerateReportDetails(StakerWorkOrderid, UserNameOrIPAddress, ViewScannedOnly=True)
    t = loader.get_template('/opt/coopgis/djangoproject/templates/stakergeneratereport.html')
    c = Context({'LoginStatus' : LoginStatus, 'GenerateReportStatus': GenerateReportStatus, 'ReportLocation': ReportLocation})
    return HttpResponse(t.render(c))

@transaction.commit_on_success
def ViewInspected(request, StakerWorkOrderid):
    ApplicationName=djangoproject.settings.COOPGISStakerApplicationName
    UserNameOrIPAddress=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=False, ApplicationName=ApplicationName)
    LoginStatus, applicationPermission=COOPGIS_Misc.CheckLoginPermissions(request, ApplicationName)
    if(not applicationPermission):
        t = loader.get_template('/opt/coopgis/djangoproject/templates/stakergeneratereport.html')
        c = Context({'LoginStatus' : LoginStatus})
        return HttpResponse(t.render(c))
    GenerateReportStatus, ReportLocation=COOPGIS_FormStaker.GenerateReportDetails(StakerWorkOrderid, UserNameOrIPAddress, ViewInspectedOnly=True)
    t = loader.get_template('/opt/coopgis/djangoproject/templates/stakergeneratereport.html')
    c = Context({'LoginStatus' : LoginStatus, 'GenerateReportStatus': GenerateReportStatus, 'ReportLocation': ReportLocation})
    return HttpResponse(t.render(c))



@transaction.commit_on_success
def GenerateAddRemoveReport(request, StakerWorkOrderid):
    ApplicationName=djangoproject.settings.COOPGISStakerApplicationName
    UserNameOrIPAddress=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=False, ApplicationName=ApplicationName)
    LoginStatus, applicationPermission=COOPGIS_Misc.CheckLoginPermissions(request, ApplicationName)
    if(not applicationPermission):
        t = loader.get_template('/opt/coopgis/djangoproject/templates/stakergenerateaddremovereport.html')
        c = Context({'LoginStatus' : LoginStatus})
        return HttpResponse(t.render(c))
    stakerWorkOrder=StakerWorkOrder.objects.filter(id__exact=int(StakerWorkOrderid))[0]
    stakerWorkOrder.ReportAddRemoveCreate()
    GenerateReportStatus='An Add/Remove Report was generated for ' + str(stakerWorkOrder.id) + ':  ' + stakerWorkOrder.Name
    ReportLocation='/coopgisstakerworkorders/' + str(StakerWorkOrderid) + 'AddRemove' + '.pdf'
    t = loader.get_template('/opt/coopgis/djangoproject/templates/stakergenerateaddremovereport.html')
    c = Context({'LoginStatus' : LoginStatus, 'GenerateReportStatus': GenerateReportStatus, 'ReportLocation': ReportLocation})
    return HttpResponse(t.render(c))

@transaction.commit_on_success
def PrimarySecondaryReport(request, StakerWorkOrderid):
    ApplicationName=djangoproject.settings.COOPGISStakerApplicationName
    UserNameOrIPAddress=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=False, ApplicationName=ApplicationName)
    LoginStatus, applicationPermission=COOPGIS_Misc.CheckLoginPermissions(request, ApplicationName)
    if(not applicationPermission):
        t = loader.get_template('/opt/coopgis/djangoproject/templates/stakerprimarysecondaryreport.html')
        c = Context({'LoginStatus' : LoginStatus})
        return HttpResponse(t.render(c))
    stakerWorkOrder=StakerWorkOrder.objects.filter(id__exact=int(StakerWorkOrderid))[0]
    Assemblies=Assembly.objects.filter(StakerWorkOrder=stakerWorkOrder)
    StringList=[]
    for i in Assemblies:
        if(i.PrimaryIndicator and not i.SecondaryIndicator and not i.ServiceIndicator):
            Type=' Primary  '
        elif(not i.PrimaryIndicator and i.SecondaryIndicator and not i.ServiceIndicator):
            Type=' Secondary '
        elif(not i.PrimaryIndicator and not i.SecondaryIndicator and i.ServiceIndicator):
            Type=' Service  '
        else:
            Type=' Unknown  '

        if(i.Station):
            StringList.append(str(i.CompatibleUnit.Name).ljust(40, ' ') + Type.ljust(23, ' ') + i.InstallStatus.Name.ljust(15) + ' Station ' + str(i.Station.id).rjust(15, ' ') + '  TagNumbers:  ' + COOPGIS_FormStaker.GetNearbyTags(i))
        elif(i.Span):
            StringList.append(str(i.CompatibleUnit.Name).ljust(40, ' ') + Type.ljust(23, ' ') + i.InstallStatus.Name.ljust(15) + ' Span    ' + str(i.Span.id).rjust(15, ' ') + '  TagNumbers:  ' + COOPGIS_FormStaker.GetNearbyTags(i))
    StringList.sort()
    String='\n'.join(StringList)
    t = loader.get_template('/opt/coopgis/djangoproject/templates/stakerprimarysecondaryreport.html')
    c = Context({'LoginStatus' : LoginStatus, 'Details': String, 'StakerWorkOrderid': stakerWorkOrder.id,
                 'StakerWorkOrderName': stakerWorkOrder.Name})
    return HttpResponse(t.render(c))


@transaction.commit_on_success
def QuickGenerateWorkOrder(request, StakerWorkOrderid):
    ApplicationName=djangoproject.settings.COOPGISStakerApplicationName
    UserNameOrIPAddress, DefaultMap=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=True, ApplicationName=ApplicationName)
    LoginStatus, applicationPermission=COOPGIS_Misc.CheckLoginPermissions(request, ApplicationName)
    if(not applicationPermission):
        t = loader.get_template('/opt/coopgis/djangoproject/templates/stakerquickgenerateworkorder.html')
        c = Context({'LoginStatus' : LoginStatus})
        return HttpResponse(t.render(c))
    form=COOPGIS_FormMisc.BuildForm(request, ApplicationName + 'QuickGenerate', DefaultMap, Assemblies=[])
    COOPGIS_FormGeography.GetAndSetDefaultMap(form, ApplicationName, UserNameOrIPAddress)
    stakerWorkOrder=StakerWorkOrder.objects.filter(id__exact=int(StakerWorkOrderid))[0]
    polygon=COOPGIS_FormStaker.ProcessStakerQuickGenerateForm(form, stakerWorkOrder, UserName=UserNameOrIPAddress)
    Assemblies=COOPGIS_Misc.GetAssembliesWithinPolygon(polygon)
    form=COOPGIS_FormMisc.BuildForm(request, ApplicationName + 'QuickGenerate', DefaultMap, Assemblies=Assemblies)
    form=COOPGIS_FormStaker.PopulateStakerQuickGenerateForm(form, stakerWorkOrder, Assemblies=Assemblies)
    COOPGIS_DynamicTemplate.UpdateStakerQuickGenerateWorkOrderTemplate(len(Assemblies), UserNameOrIPAddress)
    MapFileName, LayerName =COOPGIS_Misc.GenerateDynamicMapFile(ApplicationName, UserNameOrIPAddress) 
    OpenLayersZoom=COOPGIS_Ajax.GetOpenLayersZoom(None, None, Zoom=15)
    OpenLayersJavaScriptHeading=COOPGIS_Ajax.GetOpenLayersJavaScriptHeading()
    OpenLayersJavaScript=COOPGIS_Ajax.GetOpenLayersJavaScript(OpenLayersZoom, MapFileName, LayerName,
                            OpenLayersJavaScriptHeading, GeometryFeature = 'Polygon')
    t = loader.get_template('/opt/coopgis/djangoproject/templates/stakerquickgenerateworkorder' + UserNameOrIPAddress + '.html')
    c = Context({'LoginStatus' : LoginStatus, 'form':form, 
                 'StakerWorkOrderid': stakerWorkOrder.id,
                 'StakerWorkOrderName': stakerWorkOrder.Name,
                 'OpenLayersJavaScriptHeading': OpenLayersJavaScriptHeading,
                 'OpenLayersJavaScript': OpenLayersJavaScript})
    return HttpResponse(t.render(c))

@transaction.commit_on_success
def StakerWorkOrderHistoryReport(request):
    ApplicationName=djangoproject.settings.COOPGISStakerApplicationName
    UserNameOrIPAddress=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=False, ApplicationName=ApplicationName)
    LoginStatus, applicationPermission=COOPGIS_Misc.CheckLoginPermissions(request, ApplicationName)
    if(not applicationPermission):
        t = loader.get_template('/opt/coopgis/djangoproject/templates/stakerworkorderhistoryreport.html')
        c = Context({'LoginStatus' : LoginStatus})
        return HttpResponse(t.render(c))
    #Perform Data Gathering Tasks
    Temp = []
    Histories=StakerAssemblyHistory.objects.all().order_by('id')
    Temp.append('id'.ljust(15) + 'Compatible Unit'.ljust(50) + 'StakerWorkOrderid'.ljust(25) + 'Date'.ljust(20) + 'InstallStatus'.ljust(15) +
                'Quantity'.ljust(15))
    for i in Histories:
        if(i.InstallIndicator):
            InstallStatus='Install'
        else:
            InstallStatus='Remove'
        if(i.Line):
            Quantity=int(i.Line.length)
        else:
            Quantity=1
        Temp.append(str(i.id).ljust(15) + str(i.CompatibleUnit.Name).ljust(50) + str(i.StakerWorkOrder.id).ljust(25) + str(i.Date).ljust(20) +
                    str(InstallStatus).ljust(15) + str(Quantity).ljust(15))
    Preformatted='\n'.join(Temp)
    #End Data Gathering Tasks
    t = loader.get_template('/opt/coopgis/djangoproject/templates/stakerworkorderhistoryreport.html')
    c = Context({'LoginStatus' : LoginStatus, 'Preformatted': Preformatted})
    return HttpResponse(t.render(c))

@transaction.commit_on_success
def ReviewWorkOrders(request):
    ApplicationName=djangoproject.settings.COOPGISStakerApplicationName
    UserNameOrIPAddress=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=False, ApplicationName=ApplicationName)
    LoginStatus, applicationPermission=COOPGIS_Misc.CheckLoginPermissions(request, ApplicationName)
    if(not applicationPermission):
        t = loader.get_template('/opt/coopgis/djangoproject/templates/stakermainmenu.html')
        c = Context({'LoginStatus' : LoginStatus})
        return HttpResponse(t.render(c))
    from operator import itemgetter
    StakerWorkOrders=[]
    ErrorList=[]
    for i in StakerWorkOrder.objects.all():
        if not '-' in i.WorkOrderNumber:
            ErrorList.append(i)
            continue
        ZoneList=i.WorkOrderNumber.split('-')
        try:
            Zone=int(ZoneList[0])
        except ValueError:
            try:
                Zone=float(ZoneList[0])
            except ValueError:
                ErrorList.append(i)
                continue
        try:
            ZoneSpecificNumber=int(ZoneList[1])
        except ValueError:
            try:
                ZoneSpecificNumber=float(ZoneList[1])
            except ValueError:
                ErrorList.append(i)
                continue
        StakerWorkOrders.append((Zone, ZoneSpecificNumber, i.Name))
    WorkOrdersByZoneSpecificNumber=sorted(StakerWorkOrders, key=itemgetter(1))
    WorkOrdersByZone=sorted(WorkOrdersByZoneSpecificNumber, key=itemgetter(0))
    Temp=[]
    Temp.append(str(len(ErrorList)) + ' Invalid WorkOrderNumbers\n')
    Temp.append('ID'.ljust(10) + 'Work Order #'.ljust(15) + 'Name')
    for i in ErrorList:
        Temp.append(str(i.id).ljust(10) + i.WorkOrderNumber.ljust(15) + i.Name)
    Temp.append('\n\nValid WorkOrderNumbers')
    Temp.append('Zone'.ljust(10) + 'SubZone'.ljust(15) + 'Name')
    for i in WorkOrdersByZone:
        Temp.append(str(i[0]).ljust(10) + str(i[1]).ljust(15) + i[2])
    Preformatted='\n'.join(Temp)
    t = loader.get_template('/opt/coopgis/djangoproject/templates/stakerviewworkorders.html')
    c = Context({'LoginStatus' : LoginStatus, 'Preformatted': Preformatted})
    return HttpResponse(t.render(c))
